# -*- coding:utf-8 -*-

import logging
import os
import datetime
from logging import handlers

import colorlog
from colorlog.formatter import ColoredRecord, ColoredFormatter

from Util import config
from Util.util import Singleton


class MyConsoleFormatter(ColoredFormatter):
    def formatMessage(self, record: logging.LogRecord) -> str:
        escapes = self._escape_code_map(record.levelname)
        wrapper = ColoredRecord(record, escapes)
        message = super().formatMessage(wrapper)  # type: ignore
        message = self._append_reset(message, escapes)
        m = message.replace(os.sep, "/").split(config.rootPath.replace(os.sep, "/"))
        if len(m) > 1:
            message = m[0] + m[1][1:]
        return message


class MyFileFormatter(logging.Formatter):
    def formatMessage(self, record):
        message = super().formatMessage(record)
        m = message.replace(os.sep, "/").split(config.rootPath.replace(os.sep, "/"))
        if len(m) > 1:
            message = m[0] + m[1][1:]
        return message


@Singleton
class Logger(object):

    def __init__(self):
        self.fullLogPath = os.path.join(config.logPath, "fullLogs", "full.log")
        self.errorLogPath = os.path.join(config.logPath, "errorLogs", "error.log")

        self.logger = logging.getLogger('WebUIAuto')
        self.logger.setLevel(logging.DEBUG)

        # 记录所有的日志
        full_handler = handlers.TimedRotatingFileHandler(self.fullLogPath, when='midnight', interval=1,
                                                         backupCount=config.globalLogConf.fullLog.backupCount,
                                                         atTime=datetime.datetime(year=datetime.datetime.now().year,
                                                                                  month=datetime.datetime.now().month,
                                                                                  day=datetime.datetime.now().day),
                                                         encoding="UTF-8")
        # full_handler = handlers.RotatingFileHandler(filename=self.fullLogPath, encoding="utf-8")
        full_handler.setFormatter(MyFileFormatter(config.globalLogConf.fullLog.formatter,
                                                  datefmt=config.globalLogConf.datetimefmt))
        full_handler.setLevel(eval(f"logging.{config.globalLogConf.fullLog.Level.upper()}"))

        # 记录错误级别以上的日志
        error_handler = logging.FileHandler(self.errorLogPath, encoding="UTF-8")
        error_handler.setLevel(eval(f"logging.{config.globalLogConf.errorLog.Level.upper()}"))
        error_handler.setFormatter(MyFileFormatter(config.globalLogConf.errorLog.formatter,
                                                   datefmt=config.globalLogConf.datetimefmt))

        # 控制台输出日志
        console_handle = colorlog.StreamHandler()
        formatter = MyConsoleFormatter(
            fmt=config.globalLogConf.consoleLog.formatter,
            datefmt=config.globalLogConf.datetimefmt,
            log_colors={k.upper(): v for k, v in config.globalLogConf.consoleLog.color.items()})
        console_handle.setFormatter(formatter)
        console_handle.setLevel(eval(f"logging.{config.globalLogConf.consoleLog.Level.upper()}"))

        # 将 handler 添加到 logger 中
        self.logger.addHandler(full_handler)
        self.logger.addHandler(error_handler)
        self.logger.addHandler(console_handle)
        self.debug, self.info, self.warning, self.error, self.critical = self.setProperty()

    def setProperty(self):
        debug = self.logger.debug
        info = self.logger.info
        warning = self.logger.warning
        error = self.logger.error
        critical = self.logger.critical
        return debug, info, warning, error, critical


logger = Logger()

if __name__ == '__main__':
    logger.debug("测试debug")
    logger.info("测试info")
    logger.warning("测试warning")
    logger.error("测试error")
    logger.critical("测试critical")
